package com.example.aspects;

import com.example.annotations.AddTraceId;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import java.util.UUID;

@Aspect
@Component
public class TraceIdAspect {

    @Before("@annotation(addTraceId)")
    public void addTraceId(JoinPoint joinPoint, AddTraceId addTraceId) {
        String traceId = generateTraceId();
        MDC.put("traceId", traceId);
    }

    @After("@annotation(addTraceId)")
    public void removeTraceId(JoinPoint joinPoint, AddTraceId addTraceId) {
        MDC.remove("traceId");
    }

    private String generateTraceId() {
        // 根据业务需求生成唯一的 traceId
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
}
